package com.briup.estore.web.servlet;

import com.briup.estore.bean.ShopAddress;
import com.briup.estore.service.ShopAddressService;
import com.briup.estore.service.impl.ShopAddressServiceImpl;
import com.briup.estore.util.CommonUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addShopAddress")
public class AddShopAddressServlet extends HttpServlet {
    private ShopAddressService shopAddressService;

    {
        shopAddressService = new ShopAddressServiceImpl();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("receiveName");
        String address = req.getParameter("address");
        String phone = req.getParameter("phone");
        Integer userId = CommonUtil.getUserId(req);

        ShopAddress shopAddress = new ShopAddress();
        shopAddress.setReceivename(name);
        shopAddress.setAddress(address);
        shopAddress.setPhone(phone);
        shopAddress.setCustomerId(userId);

        // 新增
        shopAddressService.addShopAddress(shopAddress);

        // 仅查询新增的那一条
        ShopAddress newAddress = shopAddressService.findAddressById(userId);
        // 封装成json格式的字符串
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(newAddress);
        System.out.println(jsonStr);
        // 讲json字符串写回到客户端
        resp.getWriter().println(jsonStr);

    }
}
